<template>
  <view class="page-bg">
    <!-- 信息完善度 -->
    <view class="progress-bar-wrap" v-if="isBoss==0 " >
      <!-- <view class="progress-label">
        信息完善度
        <text class="progress-value">{{ percent }}%</text>
      </view>
      <progress :percent="percent" stroke-width="8" active color="#3a7afe" backgroundColor="#e5e6eb" />
      <view class="progress-tip">完善企业信息可提升可信度，获得更多关注</view> -->
      <view class="form-label">身份<text class="red">*</text></view>
      <picker @change="bindPickerChange"  :value="index" :range="array">
          <view class="form-input">{{array[index] || '请选择你的身份' }}</view>
        </picker>
    </view>

    <!-- 企业logo上传 -->
    <view class="section" v-if="index==0" >
      <view class="section-title">企业logo<text class="red">*</text></view>
      <view class="logo-upload-row">
        <up-upload
          :fileList="logoList"
          @afterRead="afterReadLogo"
          @delete="deleteLogo"
          :maxCount="1"
          width="140"
          height="140"
          name="logo"
        ></up-upload>
        <view class="logo-tip">
          建议尺寸200×200px，支持JPG、PNG格式，文件大小不超过2MB
        </view>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="section" v-if="index==0" >
      <view class="section-title">基本信息</view>
      <view class="form-label">企业名称<text class="red">*</text></view>
      <input class="form-input" :disabled="companyId ? true :false " v-model="form.name" placeholder="请输入企业名称" />

      <!-- <view class="form-label">企业简称</view>
      <input class="form-input" v-model="form.shortName" placeholder="请输入企业简称" /> -->

      <view class="form-label">企业规模</view>
      <input class="form-input" type="number" v-model="form.scale" placeholder="请输入企业规模" />

      <view class="form-label">统一社会信用代码<text class="red">*</text></view>
      <input class="form-input" :disabled="companyId ? true :false " v-model="form.code" placeholder="请输入18位统一社会信用代码" />
      <view class="form-tip">填写后将用于企业身份验证</view>

      <view class="form-label">企业类型<text class="red">*</text></view>
      <picker :range="companyTypes" @change="companyTypeChange" >
        <view class="form-input picker-input">
          {{ companyTypes[form.typeIdx] || '请选择企业类型' }}
        </view>
      </picker>

      <view class="form-label">所属行业<text class="red">*</text></view>
      <picker :range="industryList" @change="industryChange" >
        <view class="form-input picker-input">
          {{ industryList[form.industryIdx] || '请选择所属行业' }}
        </view>
      </picker>
      <view class="form-label">成立时间<text class="red">*</text></view>
      <picker @change="bindDateChange" :value="form.date" mode="date" start="1990-01-01" end="2100-12-31">
        <view class="form-input">
          {{ form.date || '请选择成立时间' }}
        </view>
      </picker>
    </view>

    <!-- 联系信息 -->
    <view class="section" v-if="index==0" >
      <view class="section-title">联系信息</view>
      <view class="form-label">负责人<text class="red">*</text></view>
      <input class="form-input" v-model="form.principal" placeholder="请输入负责人" />

      <view class="form-label">联系人<text class="red">*</text></view>
      <input class="form-input" v-model="form.contact" placeholder="请输入联系人" />

      <!-- <view class="form-label">岗位<text class="red">*</text></view>
      <input class="form-input" v-model="form.position" placeholder="请输入岗位" /> -->

      <view class="form-label">联系电话<text class="red">*</text></view>
      <input class="form-input" v-model="form.phone" placeholder="请输入联系电话" />

      <view class="form-label">联系邮箱</view>
      <input class="form-input" v-model="form.email" placeholder="请输入联系邮箱" />

      <view class="form-label">企业地址<text class="red">*</text></view>
      <input class="form-input" v-model="form.address" placeholder="请输入企业地址" />
    </view>
    <!-- 员工联系信息 -->
    <view class="section" v-if="index==1" >
      <view class="section-title">联系信息</view>

      <view class="form-label">员工姓名<text class="red">*</text></view>
      <input class="form-input" v-model="user.empName" placeholder="请输入员工姓名" />

      <view class="form-label">岗位<text class="red">*</text></view>
      <input class="form-input" v-model="user.position" placeholder="请输入岗位" />

      <view class="form-label">联系电话<text class="red">*</text></view>
      <input class="form-input" v-model="user.phonenumber" placeholder="请输入联系电话" />

      <!-- <view class="form-label">联系邮箱</view>
      <input class="form-input" v-model="user.email" placeholder="请输入联系邮箱" /> -->

      <view class="form-label">入会码</view>
      <input class="form-input" v-model="user.membershipCode" placeholder="请输入入会码"  />
      <view class="form-label">员工头像</view>
      <view class="avatar-container">
        <button type="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseavatar"
            class="btn avatar" style="width:200rpx;height:200rpx;padding: 0;margin: 0;" >
            <image :src="imgUrl+user.avatar" mode="aspectFill" style="width: 100%;height: 100%;" />
        </button>
        <view style="font-size: 24rpx;color: #ccc;text-indent: 20rpx;">点击更换头像</view>
      </view>
    </view>

    <!-- 固定底部按钮 -->
    <view class="fixed-footer">
      <button class="save-btn" @click="onSave">提交</button>
      <!-- <view class="footer-tip">
        提交后将进行审核，审核通过后不可修改企业名称和信用代码
      </view> -->
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import {addEnterprise,editEnterprise,getEnterpriseInfo,updateEmployee,getEmployeeInfo} from '@/api/index'
import {baseUrl,imgUrl } from '@/config/index'
const percent = ref(65)
let companyId = ref('')
onMounted(()=>{
  let firstLogin = uni.getStorageSync('firstLogin')
  if (firstLogin == 0) {
    isBoss.value = 0
    index.value = 0
    getEmployeeInfo().then(res => {
      console.log(res);
      if (res.code == 200 && res.data) {
        user.value.empName = res.data.empName
        user.value.phonenumber = res.data.phonenumber
        // user.value.membershipCode=res.data.membershipCode
        user.value.position = res.data.position
        user.value.id = res.data.id
        user.value.avatar=res.data.avatar
      }
    })
  } else {
    getEmployeeInfo().then(res => {
      console.log(res);
      if (res.code == 200 && res.data) {
        console.log(res.data);
        user.value.empName = res.data.empName
        user.value.phonenumber = res.data.phonenumber
        // user.value.membershipCode=res.data.membershipCode
        user.value.position = res.data.position
        user.value.id = res.data.id
        user.value.avatar=res.data.avatar
        if (res.data.isBoss == 0) {
          getEnterpriseInfo().then(res => {
            console.log(res);
            if (res.code == 200 && res.data) {
              companyId.value = res.data.id
              logoList.value = [{ url: imgUrl + res.data.logoUrl }]
              form.name = res.data.enterpriseName
              form.code = res.data.enterpriseCode
              form.scale = res.data.enterpriseScale
              form.typeIdx = companyTypes.findIndex(item => item == res.data.enpType)
              form.industryIdx = industryList.findIndex(item => item == res.data.industry)
              form.date = res.data.establishDate
              form.principal = res.data.principal
              form.contact = res.data.contactPerson
              form.phone = res.data.contactPhone
              form.email = res.data.contactEmail
              form.address = res.data.address
              form.enterpriseName = res.data.enterpriseName
              index.value = 0
              isBoss.value = 0
            }
          })
        }else{
          index.value = 1
          isBoss.value = 1
        }
      }
    })
  }

})
let isBoss = ref(1)
const logoList = ref([])
let logoPath = ref('')
let array=ref(['企业负责人','企业员工'])
const index=ref(0)
const bindPickerChange=(e) => { 
    index.value=e.detail.value
}
const form = reactive({
  name: '',
  shortName: '',
  code: '',
  typeIdx: 0,
  industryIdx: 0,
  contact: '',
  phone: '',
  email: '',
  address: '',
  scale: '',
  date:'',
  // position:''
})
let user=ref({
  empName:'',
  phonenumber:'',
  membershipCode:'',
  position:'',
  id:''
})

const companyTypes = [
  '有限责任公司', '股份有限公司', '国有企业', '集体企业', '合伙企业', '个体工商户', '外商投资企业'
]
const industryList = [
  '信息技术', '制造业', '建筑业', '批发和零售业', '金融业', '交通运输', '教育', '医疗卫生', '其他'
]
const companyTypeChange=(e) => { 
    form.typeIdx=e.detail.value
}
const industryChange=(e) => { 
    form.industryIdx=e.detail.value
}
const bindDateChange=(e) => { 
    form.date=e.detail.value
}
const onChooseavatar=(e)=>{
  uni.uploadFile({
			url: baseUrl+'common/upload', //仅为示例，非真实的接口地址
			filePath: e.detail.avatarUrl,
			name: 'file',
			success: (res) => {
				user.value.avatar=JSON.parse(res.data).fileName
        console.log(res);
        
			}
		});
}
// logo上传
const afterReadLogo = async (event) => {
  const result =await uploadFilePromise(event.file.url)
  logoList.value = [{
    url: imgUrl + JSON.parse(result).fileName,
    status: 'success'
  }]
  logoPath.value = JSON.parse(result).fileName
}
const deleteLogo = () => {
  logoList.value = []
}
const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: baseUrl+'common/upload', // 仅为示例，非真实的接口地址
      filePath: url,
      name: 'file',
      formData: {
        user: 'test',
      },
      success: (res) => {
        console.log(res);
        
          resolve(res.data);
        // setTimeout(() => {
        // }, 1000);
      },
    });
  });
};
const onSave = () => {
  // 提交逻辑
  // 企业负责人
  if(index.value==0){
    // 判断非空
    if(form.name==''){
      uni.showToast({ title: '请输入企业名称', icon: 'none' })
      return
    }
    if(form.code==''){
      uni.showToast({ title: '请输入统一社会信用代码', icon: 'none' })
      return
    }
    if(form.code.length!=18){
      uni.showToast({ title: '统一社会信用代码应为18位', icon: 'none' })
      return
    }
    if(form.scale==''){
      uni.showToast({ title: '请输入企业规模', icon: 'none' })
      return
    }
    
    if(form.date==''){
      uni.showToast({ title: '请选择成立时间', icon: 'none' })
      return
    }
    if(form.principal==''){
      uni.showToast({ title: '请输入负责人', icon: 'none' })
      return
    }
    if(form.contact==''){
      uni.showToast({ title: '请输入联系人', icon: 'none' })
      return
    }
    if(form.phone==''){
      uni.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }
    const phoneReg = /^1[3-9]\d{9}$/
    if(!phoneReg.test(form.phone)){
      uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }
    if(form.address==''){
      uni.showToast({ title: '请输入企业地址', icon: 'none' })
      return
    }

    
  uni.showToast({ title: '已提交', icon: 'success' })
    // return
    if(companyId.value==''){
      addEnterprise({
        enterpriseName:form.name,
        enterpriseCode:form.code,
        enterpriseScale:form.scale,
        logoUrl:logoPath.value,
        enpType:companyTypes[form.typeIdx],
        industry:industryList[form.industryIdx],
        establishDate:form.date,
        principal:form.principal,
        contactPerson:form.contact,
        contactPhone:form.phone,
        contactEmail:form.email,
        address:form.address
      }).then(res=>{
        if(res.code==200){
          uni.showToast({ title: '已提交', icon: 'success' })
          uni.setStorageSync('firstLogin',1)
          setTimeout(() => {
            uni.navigateBack()
          }, 1000);
        }else{
          uni.showToast({ title: res.msg, icon: 'none' })
        }
      })
    }else{
      editEnterprise({
        id:companyId.value,
        enterpriseName:form.name,
        enterpriseCode:form.code,
        enterpriseScale:form.scale,
        logoUrl:logoPath.value,
        enpType:companyTypes[form.typeIdx],
        industry:industryList[form.industryIdx],
        establishDate:form.date,
        principal:form.principal,
        contactPerson:form.contact,
        contactPhone:form.phone,
        contactEmail:form.email,
        address:form.address
      }).then(res=>{
        if(res.code==200){
          uni.setStorageSync('firstLogin',1)
          uni.showToast({ title: '已提交', icon: 'success' })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000);
        }else{
          uni.showToast({ title: res.msg, icon: 'none' })
        }
      })
    }
  }else{
    // 企业员工
    if(user.value.empName==''){
      uni.showToast({ title: '请输入员工姓名', icon: 'none' })
      return
    }
    if(user.value.position==''){
      uni.showToast({ title: '请输入岗位', icon: 'none' })
      return
    }
    if(user.value.phonenumber==''){
      uni.showToast({ title: '请输入联系电话', icon: 'none' })
      return
    }
    const phoneReg = /^1[3-9]\d{9}$/
    if(!phoneReg.test(user.value.phonenumber)){
      uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
      return
    }
    updateEmployee(user.value).then(res=>{
      if(res.code==200){
        uni.showToast({ title: '已提交', icon: 'success' })
        uni.setStorageSync('firstLogin',1)
        setTimeout(() => {
          uni.navigateBack()
        }, 1000);
      }else{
        uni.showToast({ title: res.msg, icon: 'none' })

      }
    })
  }
}
</script>

<style scoped>
.page-bg {
  background: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 180rpx;
  box-sizing: border-box;
  overflow: hidden;
}
.progress-bar-wrap {
  background: #fff;
  padding: 28rpx 24rpx 12rpx 24rpx;
  margin-bottom: 18rpx;
}
.progress-label {
  font-size: 30rpx;
  color: #222;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.progress-value {
  color: #3a7afe;
  font-size: 28rpx;
  font-weight: normal;
}
.progress-tip {
  color: #888;
  font-size: 24rpx;
  margin-top: 8rpx;
}
.section {
  background: #fff;
  border-radius: 18rpx;
  margin: 18rpx 0 0 0;
  padding: 28rpx 24rpx 18rpx 24rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 18rpx;
}
.logo-upload-row {
  display: flex;
  align-items: center;
  gap: 24rpx;
}
.logo-tip {
  color: #888;
  font-size: 24rpx;
  margin-left: 12rpx;
  flex: 1;
}
.form-label {
  font-size: 26rpx;
  color: #222;
  margin: 18rpx 0 8rpx 0;
  font-weight: 500;
}
.red {
  color: #fa5151;
  margin-left: 6rpx;
}
.form-input {
  /* width: 100%; */
  background: #f7f8fa;
  border-radius: 12rpx;
  border: none;
  padding: 18rpx 20rpx;
  font-size: 28rpx;
  margin-bottom: 8rpx;
  color: #333;
}
.form-input:focus {
  outline: none;
  border: 1rpx solid #3a7afe;
}
.picker-input {
  /* color: #888; */
}
.form-tip {
  color: #b0b3bb;
  font-size: 22rpx;
  margin-bottom: 8rpx;
}
.fixed-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -4rpx 24rpx 0 rgba(64,158,255,0.04);
  padding: 24rpx 24rpx 32rpx 24rpx;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.save-btn {
  width: 100%;
  background: #2156f3;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  /* padding: 28rpx 0; */
  font-weight: bold;
  letter-spacing: 2rpx;
  margin-bottom: 12rpx;
}
.footer-tip {
  color: #888;
  font-size: 22rpx;
  text-align: center;
}
</style>